package com.tech.view.component.label;

import com.tech.view.common.ColorUtil;
import com.tech.view.common.FontUtil;
import com.tech.view.common.SwingTestUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Rectangle2D;

/**
 * 链接文本
 */
public class LinkText extends JComponent implements MouseListener {
	Font font;
	private String text;
	private Rectangle2D stringBounds;
	private Color color = ColorUtil.BLUE_COLOR;

	/**
	 * 使用预设的的字体
	 *
	 * @param text 链接文本
	 */
	public LinkText(String text) {
		this(text, FontUtil.SMALL_FONT);
	}

	public LinkText(String text, Font font) {
		this.text = text;

		if (font != null) this.font = font;
		stringBounds = this.font.getStringBounds(text, FontUtil.FRC);
		setPreferredSize(new Dimension((int) stringBounds.getWidth(), (int) stringBounds.getHeight()));
		setCursor(new Cursor(Cursor.HAND_CURSOR));
		addMouseListener(this);
	}

	public static void main(String[] args) {
		SwingTestUtils.test(new LinkText("注册账号"));
	}

	public Rectangle2D getStringBounds() {
		return stringBounds;
	}

	@Override
	protected void paintComponent(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		g2.setColor(color);
		g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		g2.drawString(text, 0, -(int) stringBounds.getY()); //需要注意，这个y是负数
	}

	@Override
	public void mouseClicked(MouseEvent e) {

	}

	@Override
	public void mousePressed(MouseEvent e) {
		color = ColorUtil.BLUE_COLOR;
		repaint();
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		color = ColorUtil.BLUE_COLOR.brighter();
		repaint();
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		color = ColorUtil.BLUE_COLOR.brighter();
		repaint();
	}

	@Override
	public void mouseExited(MouseEvent e) {
		color = ColorUtil.BLUE_COLOR;
		repaint();
	}

	public void setText(String text) {
		this.text = text;
	}
}
